-module(mochiweb_main).
-export([start/1, start/0, loop/1, stop/0, static/2, ex/2]).
-define(DEFAULTS, [{name, ?MODULE},
                   {port, 8000}]).

-define(MATCH_SPEC, [{'GET', {regexp, "/www/.*"}, {?MODULE, static}},
                     {'GET', {regexp, "/examples/src/.*"}, {?MODULE, static}},
                     {'GET', "/ex",    {?MODULE, ex}},
                     {'GET', "/hello", {mochiweb_hello, h}},
                     {'GET', "/hello2",{mochiweb_hello2, h}} 
                    ]).

start(_Args) ->
    ?MODULE:start().

start() ->
    mochiweb_http:start([{loop, fun ?MODULE:loop/1} | ?DEFAULTS]).

stop() ->
    mochiweb_http:stop(?MODULE).

loop(Req) ->
    Disp = ewgi_dispatcher:new(?MATCH_SPEC),
    M = ewgi_mochiweb:new(fun (Env, StartResp) -> Disp:get_handler(Env, StartResp) end),
    M:run(Req).

%% serve an exaple page. ex
ex(Env, StartResp) ->
    Qs = ewgi_api:qs(Env),
    ParsedQs = ewgi_api:parse_qs(Qs),
    Url = ewgi_api:get_value("file", ParsedQs),
    Code = ewgi_api:get_value("code", ParsedQs),
    Pwd = filename:dirname(filename:dirname(code:which(?MODULE))),
    error_logger:error_report(Pwd),
    DocRoot = filename:dirname(Pwd),
    error_logger:error_report(DocRoot),
    {ok, C} = sgte:compile_file(DocRoot++"/www/"++Url),
    StartResp({200, "OK"}, []),
    sgte:render(C, [{src, "/examples/src/"++Code++".erl"}]).
    
%% serve a static file very inefficiently
static(Env, StartResp) ->
    Url  = ewgi_api:path_info(Env),
    DocRoot = filename:dirname(filename:dirname(filename:dirname(code:which(?MODULE)))),
    {ok, C} = sgte:compile_file(DocRoot++Url),
    StartResp({200, "OK"}, []),
    sgte:render(C, []).
